package com.yugu.park.system.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.coobird.thumbnailator.Thumbnails;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.yugu.park.system.mapper.TSysFileMapper;
import com.yugu.util.DateUtil;
import com.yugu.util.ResponseUtil;
import com.yugu.util.StringUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Api(tags = {"公共图片上传"})
@RestController
@RequestMapping("/file")
public class FileController {
    @Resource
    private TSysFileMapper mapper;
    @Value("${file.path}")
    private String savePath;
    @ApiOperation(value = "公共图片上传", notes = "公共图片上传")
    @PostMapping(value = "/uploadImg")
    public ResponseUtil.Result<ModelMap> upLoadimg(ModelMap modelMap, @RequestParam("file") MultipartFile file) throws Exception {
        List<String> suffixList = Arrays.asList(new String[]{"jpg", "jpeg", "png"});
        String fileName = file.getOriginalFilename();
        String currentDateTime = DateUtil.getCurrentDateTime(new Date(), "yyyy-MM");
        String extName = file.getOriginalFilename().substring(fileName.indexOf(".") + 1);
        String newName = currentDateTime+"/"+UUID.randomUUID().toString() + "." + extName;
        File newFile = new File(savePath, newName);
        modelMap.put("path", newName);
        modelMap.put("fileName",fileName);
        modelMap.put("planFlieId", UUID.randomUUID());
        if (suffixList.contains(extName)) {
            if (!newFile.exists()) {
                newFile.mkdirs();
            }
        }
        try {
            file.transferTo(newFile);
            if(suffixList.contains(extName)) {
            	File tempFile=newFile;
            	BufferedImage originalImage = ImageIO.read(tempFile);
                int width = (int) (originalImage.getWidth() * 1);
                int height = (int) (originalImage.getHeight() * 1);
                Thumbnails.of(tempFile)
                    .size(width, height)
//                    .outputFormat("jpg")
                    .toFile(newFile);
//                tempFile.delete();
            }
        } catch (Exception e) { 
            e.printStackTrace();
        }
        return ResponseUtil.addSuccess(modelMap);
    }
	/*
	 * @ApiOperation(value = "公共图片读取", notes = "公共图片读取")
	 * 
	 * @RequestMapping(value = {"/getLoadImg/{path}"}, method = {RequestMethod.GET})
	 * public void getLoadImg(Model model, HttpServletResponse
	 * response, @PathVariable("path") String path) { FileInputStream fis = null;
	 * response.setContentType("image/jpg"); try { OutputStream out =
	 * response.getOutputStream(); File file = new File(savePath + "/" + path); fis
	 * = new FileInputStream(file); byte[] b = new byte[fis.available()];
	 * fis.read(b); out.write(b); out.flush(); } catch (Exception e) {
	 * e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); }
	 * catch (IOException e) { e.printStackTrace(); } } } }
	 */
    @ApiOperation(value = "公共图片读取", notes = "公共图片读取")
    @RequestMapping(value = {"/getLoadImg"}, method = {RequestMethod.GET})
    public void getLoadImgByFilePath(Model model, HttpServletResponse response, @RequestParam("filePath") String filePath) {
        FileInputStream fis = null;
        response.setContentType("image/jpg");
        try {
            OutputStream out = response.getOutputStream();
            File file = new File(savePath + "/" + filePath);
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @RequestMapping(value = {"/{filePath}","/{filePath}/{id}"}, method = RequestMethod.DELETE)
    @ApiOperation("删除")
    public ResponseUtil.Result<Boolean> delete(@PathVariable("filePath") String filePath,@PathVariable(name = "id",required = false) String id) {
        File file = new File(savePath + "/" + filePath);
        if(file.exists()){
            file.delete();
        }
        if(StringUtils.isNotEmpty(id)) {
            mapper.deleteById(id);
        }
        return ResponseUtil.addSuccess(true);
    }
    @DeleteMapping("/deleteFile")
    public ResponseUtil.Result<Boolean> deleteFile(@RequestParam("filePath") String filePath) {
        File file = new File(savePath + "/" + filePath);
        if(file.exists()){
            file.delete();
        }
        return ResponseUtil.addSuccess(true);
    }
}
